package ishangchao.cn.haliaeetus.versions

import android.content.Context
import android.content.Intent
import android.databinding.DataBindingUtil
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.support.v4.content.FileProvider
import android.view.LayoutInflater
import android.view.View
import android.widget.RelativeLayout
import com.kalemao.library.logutils.LogUtil
import com.kalemao.library.utils.BaseComFunc
import ishangchao.cn.haliaeetus.R
import ishangchao.cn.haliaeetus.databinding.ViewVersionUpdateBinding
import org.jetbrains.anko.find
import zlc.season.rxdownload3.RxDownload
import zlc.season.rxdownload3.core.Mission
import zlc.season.rxdownload3.core.Status
import java.io.File

/**
 * @author by dim
 * @data 2018/4/17 14:05
 * 邮箱：271756926@qq.com
 */
class ViewVersionUpdate : RelativeLayout {
    lateinit var mContext: Context
    lateinit var binding: ViewVersionUpdateBinding
    lateinit var mVersionInfo: MVersionsCheck
    private var mListener: OnVersionUpdateListener? = null

    constructor(context: Context, versionInfo: MVersionsCheck, listener: OnVersionUpdateListener) : super(context) {
        this.mContext = context
        this.mListener = listener
        val v = LayoutInflater.from(context).inflate(R.layout.view_version_update, this)
        binding = DataBindingUtil.bind(v.find(R.id.view_version_rootview))
        mVersionInfo = versionInfo
        initView()
    }

    private fun initView() {
        binding.isDownload = false
        binding.versionInfo = mVersionInfo
        binding.closeClick = (View.OnClickListener {
            if (mListener != null) {
                mListener!!.onViewClose()
            }
        })

        binding.updateClick = (View.OnClickListener {
            showDownload()
        })
    }

    private fun showDownload() {
        binding.isDownload = true
        binding.viewVersionLoading.visibility = View.VISIBLE
        var savePath = Environment.getExternalStorageDirectory().path.toString()
        var saveName = "zdyp" + BaseComFunc.getAppVersionName(mContext) + System.currentTimeMillis()
        var mission = Mission(mVersionInfo.download_url, saveName, savePath)
        RxDownload.create(mission!!).observeOn(
                io.reactivex.android.schedulers.AndroidSchedulers.mainThread()).subscribe { t: Status ->
            RxDownload.start(mission!!).subscribe()
            LogUtil.d("AAAA", "download---------------------------------------")
            LogUtil.d("AAAA format = ", t.formatString())
            LogUtil.d("AAAA download = ", t.formatDownloadSize())
            LogUtil.d("AAAA total = ", t.formatTotalSize())
            LogUtil.d("AAAA chunkFlag = ", t.chunkFlag)
            LogUtil.d("AAAA download = ", t.downloadSize)
            LogUtil.d("AAAA total = ", t.totalSize)

            if (t.totalSize > 0) {
                binding.viewVersionLoading.setProgress(t.downloadSize / t.totalSize.toFloat())
            }
            if (t.downloadSize > 0 && t.totalSize == t.downloadSize) {
                binding.viewVersionLoading.visibility = View.GONE
                onUploadSuccess(savePath, saveName)
                if (mListener != null) {
                    mListener!!.onDownloadSuccess()
                }
            }
        }
    }

    private fun onUploadSuccess(savePath: String, saveName: String) {
        var file = File(savePath + "/" + saveName)
        var intent = Intent()
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        intent.action = Intent.ACTION_VIEW
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            var photoURI = FileProvider.getUriForFile(mContext, "com.ewanse.zdyp.provider", file)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            intent.setDataAndType(photoURI, "application/vnd.android.package-archive")
        } else {
            intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive")
        }
        mContext.startActivity(intent)
    }

    interface OnVersionUpdateListener {
        fun onViewClose()
        fun onDownloadSuccess()
    }
}